import axios from "axios"
/**
 * 请求时间
 */
axios.defaults.timeout = 3000
/**
 * 请求地址  http://127.0.0.1:8888/api/private/v1/
 */
axios.defaults.baseURL = process.env.VUE_APP_API
import { ElMessage, ElLoading } from 'element-plus'
/**
 * 请求拦截器
 */
let Loading;
axios.interceptors.request.use(confirg => {
  let token = sessionStorage.getItem('token')
  confirg.headers.Authorization = token
  Loading=ElLoading.service({
    lock: true,
    text: '拼命加载中...',
    background: 'rgba(0, 0, 0, 0.7)',
    spinner:''
    
  })
  return confirg

}, error => Promise.reject(error))


/**
 * 相应拦截
 */
axios.interceptors.response.use(response => {
  Loading.close()
  const {data,meta} = response.data
  if (meta.status == 200 || meta.status == 201) {
    ElMessage({
      message: meta.msg,
      type: 'success',
    })
  }else{
    ElMessage({
      message: meta.msg,
      type: 'error',
    })
  }

  return response.data
}, error => {
  const msg = error.toString()
 
  if (msg.includes('timeout')) {
    ElMessage({
      message: '请求超时',
      type: 'error',
    })
    Loading.close()
    return Promise.reject(error)
  }
  if (msg.includes('Network Error')) {
    ElMessage({
      message: '网络错误，请检查网络',
      type: 'error',
    })
    Loading.close()
    return Promise.reject(error)
  }
  const { status } = error.response
  switch (status) {
    case 401:
      ElMessage({
        message: '登录过期请重新登陆',
        type: 'error',
      })
      break
    case 404:
      const { msg } = error.response.data
      ElMessage({
        message: msg + '接口不存在',
        type: 'error',
      })
      break
    case 500:
      ElMessage({
        message: '服务器内部错误',
        type: 'error',
      })
      break
    default:
      break
  }
  return Promise.reject(error)
})

export default axios